use actix_web::HttpResponse;
use common::error::MyError;
use common::r::JsonResult;
use pem::parse;
use rsa::{PaddingScheme, PublicKey, RSAPrivateKey, RSAPublicKey};
use std::fs::File;
use std::io::Read;
use log::info;
use base64::{engine::general_purpose::STANDARD, Engine as _};

pub struct GameToolController {}

impl GameToolController {

    pub async fn get_token()-> Result<HttpResponse, MyError> {
        let plaintext = format!("{:08X}010101010101010101010101010101010101010101010101010101010101010155914510010403030101",1);

        // 读取 PEM 格式的私钥文件
        let pem_str = read_pem_file("C:/Users/laoyu/Desktop/fsdownload/publickey.pem")?;
        // 解析 PEM 文件
        let pem = parse(pem_str).unwrap();
        let public_key_der = pem.contents();
        info!("public_key_der: {:?}", public_key_der);
        // 从 DER 编码的私钥中解析出 RsaPrivateKey
        let public_key = RSAPublicKey::from_pkcs8(public_key_der).unwrap();

        // 读取 PEM 格式的私钥文件
        let pem_str = read_pem_file("C:/Users/laoyu/Desktop/fsdownload/privatekey.pem")?;
        // 解析 PEM 文件
        let pem = parse(pem_str).unwrap();
        let private_key_der = pem.contents();
        // 从 DER 编码的私钥中解析出 RsaPrivateKey
        let private_key = RSAPrivateKey::from_pkcs8(private_key_der).unwrap();
        // 使用 PKCS#1 填充进行加密（不推荐用于大块数据）
        let mut rng = rand::thread_rng();
        let hex_plaintext = hex::decode(plaintext).unwrap();
        let ciphertext = private_key.encrypt(&mut rng, PaddingScheme::new_pkcs1v15_encrypt(), &*hex_plaintext).unwrap();
        Ok(HttpResponse::Ok().json(JsonResult::ok(STANDARD.encode(ciphertext))))
    }
}


fn read_pem_file<P: AsRef<std::path::Path>>(file_path: P) -> Result<String, MyError> {
    let mut file = File::open(file_path)?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    Ok(contents)
}